<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .adBox {
            width: 300px;
            height: 400px;
            background-color: #6ff;
            position: fixed;
            right: 5px;
            bottom: 5px;
            display: none;
        }

        .adBox .close {
            position: absolute;
            right: 0;
            top: 0;
            background-color: red;
            color: #fff;
            padding: 2px;
        }
    </style>
</head>

<body>
    <div class="adBox">
        <div class="tips">距离广告关闭还有10秒</div>
        <div class="close">X</div>
    </div>
</body>
<script>
    // 延时器  
    // 延迟一段时间 执行特定的代码   => 代码只执行一次就停止
    // setTimeout(callback,delay,arg1,arg2,...argN)
    // callback  需要执行的内容(回调函数)
    // delay     延迟时间
    // arg1,arg2,...argN   如果回调函数需要接收参数,可以从第三参数开始依次传入

    // 返回值  =>  延时器对应的标号


    //  延迟5s 显示小广告 => 倒计时10秒后结束 => 在开启下一轮(延迟5s 显示小广告 => 倒计时10秒后结束)
    var adBox = document.getElementsByClassName("adBox")[0];
    var tips = document.getElementsByClassName("tips")[0];
    var closeBtn = document.getElementsByClassName("close")[0];
    var delayTimer = null;  // 记录延时器的编号
    var timer = null;       //记录计时器的编号

    loop(5000);

    // 点击关闭 1. 隐藏小广告  2. 清除延时器  3. 清除计时器
    closeBtn.onclick = function () {
        adBox.style.display = "none";
        clearTimeout(delayTimer);
        clearInterval(timer);
        // loop(10000);
    }

    function loop(delayTime) {
        delayTimer = setTimeout(function () {
            adBox.style.display = "block";

            // 倒计时10 
            var num = 10;
            tips.innerText = `距离广告关闭还有${num}秒`;
            timer = setInterval(function () {
                num--;
                tips.innerText = `距离广告关闭还有${num}秒`;
                if (num == 0) {
                    clearInterval(timer);
                    adBox.style.display = "none";
                    loop(delayTime);
                }
            }, 1000);

            console.log("广告显示!!!!!");
        }, delayTime);
    }
</script>

</html>